package cn.ecut.single;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;

/**
 * @Author ruanxin
 */
//懒汉式单例
public class LazyMan {

    private static boolean rx = false;

    private LazyMan() {

        synchronized (LazyMan.class) {
            if (rx == false) {
                rx = true;
            }else {
                throw new RuntimeException("不要试图通过反射破坏异常");
            }
        }
    }

    private volatile static LazyMan lazyMan;

    //双重检测锁模式  懒汉式单例 DCL懒汉模式
    public static LazyMan getInstance() {
        if (lazyMan == null) {
            synchronized (LazyMan.class) {
                if (lazyMan == null) {
                    lazyMan = new LazyMan();//不是原子性操作
                    /*
                     * 1、分配内存空间
                     * 2、执行构造对象，初始化对象
                     * 3、把这个对象指向这个空间
                     *
                     * 123
                     * 132 A
                     *   B //直接返回个lazyman但是此时未完成构造                    *
                     * */
                }
            }
        }

        return lazyMan;
    }

    //单线程下 单例ok
    //多线程下
    //反射
    public static void main(String[] args) throws Exception {
//        LazyMan instance = LazyMan.getInstance();
        Field rx = LazyMan.class.getDeclaredField("rx");
        rx.setAccessible(true);

        Constructor<LazyMan> declaredConstructor = LazyMan.class.getDeclaredConstructor(null);
        declaredConstructor.setAccessible(true);
        LazyMan instance = declaredConstructor.newInstance();

        rx.set(instance,false);
        LazyMan lazyMan2 = declaredConstructor.newInstance();
        System.out.println(instance);
        System.out.println(lazyMan2);
    }
}
